package com.ldy.job.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;

import static com.ldy.job.listener.NoModelDataListener.amountTool;
import static com.ldy.job.utils.ExcelUtils.RESSTR_TUIGUANGYUEBAO;
import static com.ldy.job.utils.ExcelUtils.RESSTR_XIANSHANGHUALV;

@Slf4j
public class NoModel2DataListener extends AnalysisEventListener<Map<Integer, String>> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 5;
    private static final String[] INDEX_STR = new String[8];
    private static final String[] INDEX2_STR = new String[8];
    private List<Map<Integer, String>> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    static {
        INDEX_STR[0] = "31_1";
        INDEX_STR[1] = "31_2";
        INDEX_STR[2] = "31_11";
        INDEX_STR[3] = "31_12";
        INDEX_STR[4] = "31_8";
        INDEX_STR[5] = "31_9";
        INDEX_STR[6] = "31_5";
        INDEX_STR[7] = "31_6";
    }

    static {
        INDEX2_STR[0] = "31_1";
//        INDEX2_STR[1] = "31_2";
        INDEX2_STR[1] = "31_3";
        INDEX2_STR[2] = "31_11";
        INDEX2_STR[3] = "31_12";
        INDEX2_STR[4] = "31_8";
        INDEX2_STR[5] = "31_9";
        INDEX2_STR[6] = "31_5";
        INDEX2_STR[7] = "31_6";
    }

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext context) {
//        log.info("解析行数:{}", context.readRowHolder().getRowIndex());
//        log.info("解析到一条数据:{}", data);
        cachedDataList.add(data);
        RESSTR_XIANSHANGHUALV = doCheck(data, context,INDEX_STR,RESSTR_XIANSHANGHUALV);
        RESSTR_TUIGUANGYUEBAO = doCheck(data, context,INDEX2_STR,RESSTR_TUIGUANGYUEBAO);
        if (cachedDataList.size() >= BATCH_COUNT) {
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private static String doCheck(Map<Integer, String> data, AnalysisContext context,String[] indexStr,String resStr) {
        for (String string : indexStr) {
            String[] index = string.split("_");
            if (context.readRowHolder().getRowIndex().equals(Integer.parseInt(index[0]))) {
                String s = data.get(Integer.parseInt(index[1]));
                if (!s.contains("%")) {
                    s = amountTool(s);
                }
                resStr = resStr.replaceFirst("#X#", s);
            }
        }
        return resStr;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
    }

}
